package com.gitee.demo.utils;

import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Tao on 2019/12/6
 */
public class HttpsUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpsUtils.class);

    /**
     * 组织请求参数{参数名和参数值下标保持一致}
     *
     * @param params 参数名数组
     * @param values 参数值数组
     * @return 参数对象
     */
    public static List<NameValuePair> getParams(Object[] params, Object[] values) {
        /**
         * 校验参数合法性
         */
        boolean flag = params.length > 0 && values.length > 0 && params.length == values.length;
        if (flag) {
            List<NameValuePair> nameValuePairList = new ArrayList<>();
            for (int i = 0; i < params.length; i++) {
                nameValuePairList.add(new BasicNameValuePair(params[i].toString(), values[i].toString()));
            }
            return nameValuePairList;
        } else {
            LOGGER.error("HttpClientService-line: {}, errorMsg：{}", 197, "请求参数为空且参数长度不一致");
        }
        return null;
    }

    /**
     * map 转换为 List<NameValuePair>
     *
     * @param map
     * @return
     */
    public static List<NameValuePair> convertToNameValuePairList(Map<String, Object> map) {
        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
        if (null == map) {
            return nameValuePairList;
        }

        for (Map.Entry<String, Object> mapEntry : map.entrySet()) {
            nameValuePairList.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
        }

        return nameValuePairList;
    }


    /**
     * map 转 Header【】
     *
     * @param headersMap
     * @return
     */
    public static Header[] mapConvertToHeaders(Map<String, String> headersMap) {
        List<Header> headerList = new ArrayList<>();
        if (null == headersMap) {
            return new Header[0];
        }

        for (Map.Entry<String, String> mapEntry : headersMap.entrySet()) {
            headerList.add(new BasicHeader(mapEntry.getKey(), mapEntry.getValue()));
        }

        Header[] newHeaders = new Header[headerList.size()];
        Header[] headers = headerList.toArray(newHeaders);
        return headers;
    }

}
